﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Coding4Fun.Phone.Controls;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Net.NetworkInformation;
using Microsoft.Phone.Shell;
using Newtonsoft.Json;
using RadarGlobalPro.Class;

namespace RadarGlobalPro.GUIView
{
    public partial class GroupDlg : PhoneApplicationPage
    {
        ContextMenuController myContextMenu;

        ApplicationBarController barControl;

        Status myStatus = new Status();
            
        public GroupDlg()
        {
            InitializeComponent();
            InitializeAppllication();
            InitializeContextMenu();           

            LoadmyGroup();
            LoadAllGroup();
            LoadInvateGroup();
        }
        #region CreateController
        public void InitializeContextMenu()
        {
            myContextMenu = new ContextMenuController();
            myContextMenu.Add("Join Group", true, ConextMenuEvent);
            myContextMenu.Add("Leave Group", true, ConextMenuEvent);
            myContextMenu.Add("Agree Invitation", true, ConextMenuEvent);
            myContextMenu.Add("Remove Invitation", true, ConextMenuEvent);
        }
        public void InitializeAppllication()
        {
            barControl = new ApplicationBarController(this.ApplicationBar);

            barControl.AddNewButton("Join", "/Images/appbar.join.rest.png", true, ApplicationBarButton_Click);
            barControl.AddNewButton("Delete", "/Images/appbar.delete.rest.png", true, ApplicationBarButton_Click);
            barControl.AddNewButton("Create", "/Images/appbar.add.rest.png", true, ApplicationBarButton_Click);
            barControl.AddNewButton("Find", "/Images/appbar.feature.search.rest.png", true, ApplicationBarButton_Click);
            barControl.AddNewButton("Refresh", "/Images/appbar.refresh.rest.png", true, ApplicationBarButton_Click);
        }
        #endregion

        #region Loading Data Group
        private void LoadmyGroup()
        {
            if (NetworkInterface.GetIsNetworkAvailable() != true)
            {
                return;
            }

            mySQLService.RadarServicePortTypeClient client = new mySQLService.RadarServicePortTypeClient();

            client.GetListGroupCompleted += (s, args) =>
            {
                if (args.Result == null) return;

                List<List<string>> listdata = JsonConvert.DeserializeObject<List<List<string>>>(args.Result);

                myGroup.ItemsSource = null;

                var data = GroupItem.DeserializeObject(listdata,1);

                List<AlphaKeyGroup<GroupItem>> Datasource = AlphaKeyGroup<GroupItem>.CreateGroups(data, System.Threading.Thread.CurrentThread.CurrentUICulture,

                (GroupItem gItem) => { return gItem.Title; }, true);

                myGroup.ItemsSource = Datasource;
            };
            client.GetListGroupAsync(Global.UserInfo.Username);
        }
        private void LoadAllGroup()
        {
            myStatus.ShowPopup("waitting loading group data in server ...!");

            if (NetworkInterface.GetIsNetworkAvailable() != true)
            {
                MessageBox.Show("Can't connect data... ! Please check wifi/celullar connection.");

                return;
            }

            mySQLService.RadarServicePortTypeClient client = new mySQLService.RadarServicePortTypeClient();

            client.GetAllGroupAsync(0, 300);

            client.GetAllGroupCompleted += (s, args) =>
            {
                AddResutlToAllGroup(args.Result);
            };
        }
        private void AddResutlToAllGroup(string Result)
        {
            allGroup.ItemsSource = null;

            List<List<string>> listdata = JsonConvert.DeserializeObject<List<List<string>>>(Result);

            var lsAllGroup = GroupItem.DeserializeObject(listdata);

            List<AlphaKeyGroup<GroupItem>> Datasource = AlphaKeyGroup<GroupItem>.CreateGroups(lsAllGroup, System.Threading.Thread.CurrentThread.CurrentUICulture,
            (GroupItem gItem) => { return gItem.Title; }, true);

            allGroup.ItemsSource = Datasource;

            myStatus.Abort();
        }
        private void LoadInvateGroup()
        {
            mySQLService.RadarServicePortTypeClient client = new mySQLService.RadarServicePortTypeClient();

            client.GetListGroupInvateAsync(Global.UserInfo.UserID);

            client.GetListGroupInvateCompleted += (s, args) =>
            {
                if (args.Result == null) return;

                List<List<string>> listdata = JsonConvert.DeserializeObject<List<List<string>>>(args.Result);

                InvateList.Items.Clear();

                var data = GroupItem.DeserializeObject(listdata,2);

                foreach (GroupItem item in data)

                    if (item.Status == 1)

                        InvateList.Items.Add(item);
            };
        }

        #endregion

        #region Process MenuContext in List or LongList
        private void ItemGroup_Hold(object sender, System.Windows.Input.GestureEventArgs e)
        {
            var item = ((Grid)sender).DataContext as GroupItem;

            if(item!=null)
            {
                myContextMenu.RemoveMenuItems();
                myContextMenu.AddControlHandler(sender);

                if (item.TagType == 0)
                {
                    myContextMenu.ShowMenuItems("Join Group");
                }
                if (item.TagType == 1)
                {
                    myContextMenu.ShowMenuItems("Leave Group");
                }
                if (item.TagType == 2)
                {
                    myContextMenu.ShowMenuItems("Agree Invitation","Remove Invitation");
                }
            }
        }
        #endregion

        private void ApplicationBarButton_Click(object sender, EventArgs e)
        {
            if (NetworkInterface.GetIsNetworkAvailable() != true)
            {
                //MessageBox.Show("Please check data connect wifi/cellular...");

                return;
            }

            ApplicationBarIconButton btn = (ApplicationBarIconButton)sender;

            string text = btn.Text.ToLower();

            mySQLService.RadarServicePortTypeClient client = new mySQLService.RadarServicePortTypeClient();

            if (text == "join")
            {
                ListBoxItem listItem = this.allGroup.SelectedItem as ListBoxItem;

                if (listItem != null)
                {
                    GroupItem item = listItem.Content as GroupItem;

                    client.CreateLinkerAsync(item.Id, Global.UserInfo.UserID, 0, 2);

                    client.CreateLinkerCompleted += (s, args) =>
                    {
                        if(args.Result==true)
                        {
                            MessageBox.Show("Request was sent! Please wait for a response from the leader");

                            LoadmyGroup();
                        }
                    };
                }
            }

            if (text == "refresh")
            {
                myStatus.ShowPopup("waitting loading group data in server ...!");
                LoadAllGroup();
                LoadmyGroup();
                LoadInvateGroup();
            }

            if (text == "find")
            {
                InputPrompt input = new InputPrompt();
                input.Completed += (s, args) =>
                {
                    if (args.Result == "" && args.Result == null) return;

                    client.SearchGroupCompleted += (send, recive) =>
                    {
                        AddResutlToAllGroup(recive.Result);
                    };
                    client.SearchGroupAsync(args.Result);
                };
                input.Title = "Find group by name";
                input.Message = "Please input group name your want find";
                input.Show();
            }

            if (text == "create")
            {
                InputPrompt input = new InputPrompt();

                input.Completed += (s, args) =>
                {
                    if (args.Result != "" && args.Result != null)
                    {
                        client.CreateGroupCompleted += (send, recive) =>
                        {
                            if (recive.Result == false)
                                MessageBox.Show("Group already exists or there is a problem!");
                            else
                            {
                                MessageBox.Show("Group create success! thanks for use.!");
                                LoadAllGroup();
                                LoadmyGroup();
                            }
                        };
                        client.CreateGroupAsync(Global.UserInfo.UserID, args.Result, 1, 1);
                    }
                };
                input.Title = "Create Radar group";
                input.Message = "Please input group name:";
                input.Show();
            }
        }

        private void Pivot_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            int i = MainPivot.SelectedIndex;
            switch (i)
            {
                case 0:
                    barControl.ShowButtons("Create", "Refresh");
                    break;
                case 1:
                    barControl.ShowButtons("Create", "Find", "Refresh");
                    break;
                case 2:
                    barControl.ShowButtons("Refresh");
                    break;
            }
        }

        private void myGroup_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            var item = (FrameworkElement)e.OriginalSource;

            if (item != null)
            {
                GroupItem data = item.DataContext as GroupItem;

                if (data != null)

                    NavigationService.Navigate(new Uri("/GUIView/MemberGroupDlg.xaml?groupid=" + data.Id + "&owner=" + data.MyOwner, UriKind.RelativeOrAbsolute));
            }
        }

        private void ConextMenuEvent(object sender,EventArgs e)
        {
            MenuItem mnitem = (MenuItem)sender;
            string text = mnitem.Header.ToString();

            if(text=="Join Group")
            {
                GroupItem item = mnitem.DataContext as GroupItem;

                if (item != null)
                {
                    mySQLService.RadarServicePortTypeClient client = new mySQLService.RadarServicePortTypeClient();

                   // Group item = listItem.Content as Group;

                    client.CreateLinkerAsync(item.Id, Global.UserInfo.UserID, 0, 2);

                    client.CreateLinkerCompleted += (s, args) =>
                    {
                        MessageBox.Show("Your request has been sent successfully! Please wait for confirmation.");

                        LoadmyGroup();
                    };
                }
            }
            if(text=="Leave Group")
            {
                GroupItem item = mnitem.DataContext as GroupItem;

                if (item!=null)
                {
                    mySQLService.RadarServicePortTypeClient client = new mySQLService.RadarServicePortTypeClient();

                    if (item.MyOwner == 1)
                    {
                        MessageBoxResult result = MessageBox.Show("You are the leader, if you leave the group, the group will be disbanded", "Are you want leave group?", MessageBoxButton.OKCancel);

                        if (result == MessageBoxResult.OK)
                        {
                            client.RemoveGroupAsync(item.Id);

                            client.RemoveGroupCompleted += (s, args) =>
                            {
                                if (args.Result == true)
                                {
                                    MessageBox.Show("Group:" + item.Title + " is disbanded");

                                    LoadmyGroup();

                                    LoadAllGroup();
                                }
                            };
                        }
                    }
                    else
                    {
                        MessageBoxResult result = MessageBox.Show("Are you sure you want to leave the group.", "Are you want leave group?", MessageBoxButton.OKCancel);

                        if (result == MessageBoxResult.OK)
                        {
                            client.RemoveLinkerAsync(item.Id, Global.UserInfo.UserID);

                            client.RemoveLinkerCompleted += (s, args) =>
                            {
                                if (args.Result == true)
                                {
                                    MessageBox.Show("You have left successful groups:" + item.Title);

                                    LoadmyGroup();
                                }
                            };
                        }
                    }
                }
            }
            if(text=="Agree Invitation")
            {
                ListBoxItem listItem = this.InvateList.ItemContainerGenerator.ContainerFromItem((sender as MenuItem).DataContext) as ListBoxItem;

                if (listItem != null)
                {
                    mySQLService.RadarServicePortTypeClient client = new mySQLService.RadarServicePortTypeClient();

                    GroupItem item = listItem.Content as GroupItem;

                    client.UpdateLinkerAsync(item.Id, Global.UserInfo.UserID, 0, 1);

                    client.UpdateLinkerCompleted += (s, args) =>
                    {
                        MessageBox.Show("Your request has been sent successfully!");

                        LoadmyGroup();

                        LoadInvateGroup();
                    };
                }
            }
            if(text=="Remove Invitation")
            {
                 ListBoxItem listItem = this.InvateList.ItemContainerGenerator.ContainerFromItem((sender as MenuItem).DataContext) as ListBoxItem;

                 if (listItem != null)
                 {
                    mySQLService.RadarServicePortTypeClient client = new mySQLService.RadarServicePortTypeClient();

                    GroupItem item = listItem.Content as GroupItem;

                    client.RemoveLinkerCompleted+=(s,args)=>
                    {
                        if (args.Result == true)
                        {
                            MessageBox.Show("You remove request has been successfully!");

                            LoadInvateGroup();
                        }
                    };
                    client.RemoveLinkerAsync(item.Id, Global.UserInfo.UserID);
                 }
            }
        }
    }
}